package com.xywy.me;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.constants.ErrorCode;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.DialogUtils;
import com.xywy.common.util.MLog;
import com.xywy.common.widget.MyProgress;
import com.xywy.find.JkgcItemActivity;
import com.xywy.find.JkzhArticleActivity;
import com.xywy.find.NewJkgcActivity;
import com.xywy.me.adapter.CollectAdapter;
import com.xywy.me.bean.Collect;
import com.xywy.me.bean.UserKeeper;

/**
 * 名称: 我 - 收藏 描述: 类型: JAVA 最近修改时间:${date} ${time}
 * 
 * @since 2014/8/8
 * @author xgd
 */
public class CollectActivity extends BaseActivity {
	private static final String TAG = "CollectActivity";
	private ListView lv;
	private LinearLayout noCollect;
	private CollectAdapter adapter;
	private RelativeLayout rlJkgc;
	private RelativeLayout rlJkzh;
	private TextView tvJkgc;
	private TextView tvJkzh;
	private Context mContext;
	private List<Collect> gcCollects; // 健康广场数据
	private List<Collect> zhCollects; // 健康知乎数据
	private int tabFlag = 2; // 1.健康知乎 2:健康广场
	private Intent intent;
	public static final String appid = "1001";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.me_collect);
		this.preInit();
		this.initView();
		this.loadData();
		this.setListener();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MLog.i(TAG, "onResume=========");
	}

	@Override
	protected void onPause() {
		super.onPause();
		MLog.i(TAG, "onPause=========");
	}

	@Override
	public void preInit() {
		mContext = this.context;
		adapter = new CollectAdapter(mContext);
	}

	@Override
	public void loadData() {
		sendFlag = 1;
		this.sendMsg(getString(R.string.me_collect_list)); // 获取收藏列表
	}

	@Override
	public void initView() {
		noCollect = (LinearLayout) this.findViewById(R.id.rl_me_collect_no);
		rlJkgc = (RelativeLayout) this.findViewById(R.id.rl_me_collect_jkgc);
		rlJkzh = (RelativeLayout) this.findViewById(R.id.rl_me_collect_jkzh);
		tvJkgc = (TextView) this.findViewById(R.id.tv_me_collect_jkgc);
		tvJkzh = (TextView) this.findViewById(R.id.tv_me_collect_jkzh);

		lv = (ListView) this.findViewById(R.id.lv_me_collect);
		lv.setDivider(null);

		rlJkgc.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.me_collect_biaoqiang_jkgc));
		rlJkzh.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.me_collect_biaoqiang_jkzh1));
		tvJkgc.setTextColor(this.getResources().getColor(R.color.start_bt_bg));
		rlJkzh.setBackgroundDrawable(null);
		tvJkzh.setTextColor(this.getResources().getColor(R.color.white));
	}

	public void onClickCollect(View view) {
		switch (view.getId()) {
		case R.id.tv_title_back:
			this.finish();
			break;
		case R.id.rl_me_collect_back:
			this.finish();
			break;
		case R.id.rl_me_collect_jkgc:
			gcClick();
			break;
		case R.id.rl_me_collect_jkzh:
			zhClick();
			break;
		}
	}

	/**
	 * 只显示 type=5 健康知乎 的数据
	 * 
	 * (文章所属项目) 1=>'咨询母婴', 2=>'咨询减肥', 3=>'咨询保健', 4=>'咨询饮食', 5=>'健康知乎', 6=>'母婴圈子'
	 * 7=>'问医生'
	 */
	private void zhClick() {
		tabFlag = 1;
		rlJkgc.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.me_collect_biaoqiang_jkgc1));
		rlJkzh.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.me_collect_biaoqiang_jkzh));
		tvJkzh.setTextColor(this.getResources().getColor(R.color.start_bt_bg));
		rlJkgc.setBackgroundDrawable(null);
		tvJkgc.setTextColor(this.getResources().getColor(R.color.white));

		if (null != zhCollects) {
			if (zhCollects.size() > 0) {
				lv.setVisibility(View.VISIBLE);
				noCollect.setVisibility(View.GONE);
				adapter.setData(zhCollects);
				lv.setAdapter(adapter);
			} else {
				lv.setVisibility(View.GONE);
				noCollect.setVisibility(View.VISIBLE);
			}
		}
	}

	private void gcClick() {
		tabFlag = 2;
		rlJkgc.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.me_collect_biaoqiang_jkgc));
		rlJkzh.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.me_collect_biaoqiang_jkzh1));
		tvJkgc.setTextColor(this.getResources().getColor(R.color.start_bt_bg));
		rlJkzh.setBackgroundDrawable(null);
		tvJkzh.setTextColor(this.getResources().getColor(R.color.white));

		if (gcCollects != null)
			if (gcCollects.size() > 0) {
				lv.setVisibility(View.VISIBLE);
				noCollect.setVisibility(View.GONE);
				adapter.setData(gcCollects);
				lv.setAdapter(adapter);
			} else {
				lv.setVisibility(View.GONE);
				noCollect.setVisibility(View.VISIBLE);
			}
	}

	MyProgress myProgress;

	/**
	 * 返回
	 */
	private Handler handler = new Handler() {
		private String error;

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
			if (null != myProgress) {
				myProgress.stop();
			}
			if (null != dlg) {
				dlg.dismiss();
			}

			if (msg.arg1 == ResultCode.SUCCESS) {
				if (sendFlag == 1) {
					// 解析数据
					analysisData(msg.obj.toString());
					if (tabFlag == 2) {
						// 健康广场
						// 判断 是否有收藏记录
						if (gcCollects.size() > 0) {
							lv.setVisibility(View.VISIBLE);
							noCollect.setVisibility(View.GONE);
							adapter.setData(gcCollects);
							lv.setAdapter(adapter);
						} else {
							lv.setVisibility(View.GONE);
							noCollect.setVisibility(View.VISIBLE);
						}
					} else {
						// 知乎
						// 判断 是否有收藏记录
						if (zhCollects.size() > 0) {
							lv.setVisibility(View.VISIBLE);
							noCollect.setVisibility(View.GONE);
							adapter.setData(zhCollects);
							lv.setAdapter(adapter);
						} else {
							lv.setVisibility(View.GONE);
							noCollect.setVisibility(View.VISIBLE);
						}
					}

				} else if (sendFlag == 2) {
					Toast.makeText(mContext, mContext.getString(R.string.val_delete_sus), Toast.LENGTH_LONG).show();
					adapter.getData().remove(collect);
					adapter.notifyDataSetChanged();
					lv.invalidate();
					if (adapter.getCount() == 0) {
						lv.setVisibility(View.GONE);
						noCollect.setVisibility(View.VISIBLE);
					}
				}

			} else if (msg.arg1 == ErrorCode.ERR_NO_NETWORK || msg.arg1 == ErrorCode.ERR_NO_NETWORK) {
				Toast.makeText(mContext, "网络不给力", Toast.LENGTH_LONG).show();
				lv.setVisibility(View.GONE);
				noCollect.setVisibility(View.VISIBLE);
			} else {
				try {
					JSONObject backMsg = new JSONObject(msg.obj.toString());
					error = backMsg.optString("error");
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				Toast.makeText(mContext, error, Toast.LENGTH_LONG).show();
				lv.setVisibility(View.GONE);
				noCollect.setVisibility(View.VISIBLE);
			}
		}
	};

	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;
	private int sendFlag = 1; // 1 :获取收藏数据 2:删除收藏

	// 处理网络请求
	public void sendMsg(String action) { // sendFlag //1 :获取收藏数据 2:删除收藏
		myProgress = new MyProgress(this, 10);
		myProgress.start();
		paramsParser = new Parser();
		// 封装参数
		params = new HashMap<String, Object>();
		// 请求路径
		paramsParser.action = action;
		// 请求方式
		paramsParser.request = "get";

		SharedPreferences sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
//		String userid = sp.getString("userid", "");
		String  userid = UserKeeper.getCurrentUser(this).getUserid();;
		// 请求参数
		params.put("userid", userid);

		if (sendFlag == 2) {
			params.put("type", collect.getType());
			params.put("art_id", collect.getArtId());
		}
		params.put("apptype", appid);

		paramsParser.map = params;
		// 传递上下文
		paramsParser.context = mContext;

		asyncHttpClient = AsyncHttpClient.getInstance();
		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
			handler.sendMessage(message);
		}

		public <T extends Parser> void onFailure(T parserResult, int resultCode) {
			Message message = Message.obtain();
			message.arg1 = resultCode;
			handler.sendMessage(message);
		};

		public <T extends Parser> void onNoNetWork(T paramParser, int resultCode) {
			Message message = Message.obtain();
			message.arg1 = resultCode;
			handler.sendMessage(message);
		};
	};
	private Dialog dlg;
	Collect collect;

	/**
	 * 点击删除
	 */
	private void setListener() {
		// 1. 常按弹出删除确认框
		lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				collect = (Collect) lv.getAdapter().getItem(position);
				// 弹提示框
				Bundle bundle = new Bundle();
				bundle.putString("title", mContext.getString(R.string.me_collect_delete));
				dlg = DialogUtils.creatDialog(mContext, 1, bundle, new View.OnClickListener() {
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.dialog_button_ok:
							sendFlag = 2;
							sendMsg(mContext.getString(R.string.delete_collect));
							dlg.dismiss();
							// 删除收藏
							break;
						case R.id.dialog_button_cancel:
							dlg.dismiss();
							break;
						default:
							break;
						}
					}
				});
				return true;
			}
		});

		// 2.点击进入内容详情页 1.健康知乎 2:健康广场
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				collect = (Collect) lv.getAdapter().getItem(position);
				if (tabFlag == 1) {
					intent = new Intent(mContext, JkzhArticleActivity.class);
					intent.putExtra("artid", collect.getArtId());
					// intent.putExtra("title",collect.getTitle());
					intent.putExtra("target", Integer.valueOf(collect.getType()));
					mContext.startActivity(intent);
				} else if (tabFlag == 2) {
					Intent intent = new Intent(mContext, JkgcItemActivity.class);
					// intent.putExtra("title", collect.getTitle());
					intent.putExtra(JkgcItemActivity.ID, collect.getArtId() + "");

					String title = "";
					String target = "";
					switch (Integer.parseInt(collect.getType())) {
					case 1:
						title = NewJkgcActivity.TITLE[0];
						target = NewJkgcActivity.TITLE_KEY[0];
						break;
					case 2:
						title = NewJkgcActivity.TITLE[4];
						target = NewJkgcActivity.TITLE_KEY[4];
						break;
					case 3:
						title = NewJkgcActivity.TITLE[2];
						target = NewJkgcActivity.TITLE_KEY[2];
						break;
					case 4:
						title = NewJkgcActivity.TITLE[3];
						target = NewJkgcActivity.TITLE_KEY[3];
						break;
					case 9:
						title = NewJkgcActivity.TITLE[1];
						target = NewJkgcActivity.TITLE_KEY[1];
						break;

					default:
						break;
					}
					intent.putExtra(JkgcItemActivity.TARGET, target);
					intent.putExtra(JkgcItemActivity.TITLE, title);

					mContext.startActivity(intent);
				}
			}
		});
	}

	/**
	 * @param jsonStr
	 */
	private void analysisData(String jsonStr) {
		gcCollects = Collections.synchronizedList(new ArrayList<Collect>());
		zhCollects = Collections.synchronizedList(new ArrayList<Collect>());
		// 分别实例化，进行潜拷贝
		Collect collect = new Collect();
		try {
			JSONObject jsonObject = new JSONObject(jsonStr);
			JSONArray jsonArray = jsonObject.getJSONArray("data");
			if (null != jsonArray && jsonArray.length() > 0) {
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject json = jsonArray.getJSONObject(i);
					Collect c = collect.clone();
					c.setId(json.optString("id"));
					c.setType(json.optString("type"));

					c.setArtId(json.optString("art_id"));
					c.setTitle(json.optString("title"));
					c.setPubtime(json.optString("pubtime"));
					c.setUrl(json.optString("url"));

					if (json.optInt("type") == 5) { // type=5, 为‘健康知乎’
						zhCollects.add(c);
					} else {
						gcCollects.add(c);
					}
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}
